package com.tiancheng.onecode.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.onecode.configuration.MiniAppProperties;
import com.tiancheng.onecode.convert.MerchantConvert;
import com.tiancheng.onecode.entity.*;
import com.tiancheng.onecode.enums.MerchantApplySubStatusEnums;
import com.tiancheng.onecode.enums.MerchantRegStatusEnums;
import com.tiancheng.onecode.enums.MerchantStatusEnums;
import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.feign.TCFeignClient;
import com.tiancheng.onecode.mapper.MerchantMapper;
import com.tiancheng.onecode.model.dto.*;
import com.tiancheng.onecode.model.request.admin.*;
import com.tiancheng.onecode.model.response.PageInfo;
import com.tiancheng.onecode.model.response.admin.*;
import com.tiancheng.onecode.service.*;
import com.tiancheng.onecode.trade.TradeApiClient;
import com.tiancheng.onecode.trade.TradeCache;
import com.tiancheng.onecode.trade.enums.AgreementSignSourceEnums;
import com.tiancheng.onecode.trade.enums.IdPhotoEnums;
import com.tiancheng.onecode.trade.enums.MerchantApplyStatusEnums;
import com.tiancheng.onecode.trade.model.request.*;
import com.tiancheng.onecode.trade.model.response.*;
import com.tiancheng.onecode.utils.DateTimeUtil;
import com.tiancheng.onecode.utils.JsonUtil;
import com.tiancheng.onecode.utils.QRCodeGenerator;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: kellen
 * @Description:商户管理 service
 * @Date: create in 2024/12/9 18:22
 */
@Slf4j
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements IMerchantService {

    @Value("${tc-service-config.merchantTag}")
    private String merchantTag;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private IPlatformService platformService;
    @Resource
    private IMerchantPayConfigService merchantPayConfigService;
    @Resource
    private IPlatformMerchantService platformMerchantService;
    @Resource
    private IPlatformMerchantUserService platformMerchantUserService;
    @Resource
    private IMerchantPayCertService merchantPayCertService;
    @Resource
    private IPlatformMerchantSettleRuleService platformMerchantSettleRuleService;
    @Resource
    private TradeApiClient tradeApiClient;
    @Resource
    private TCFeignClient tcFeignClient;
    @Resource
    private MiniAppProperties miniAppProperties;
    @Resource
    private IUploadService uploadService;
    @Resource
    private IMerchantPayQrService merchantPayQrService;
    @Resource
    private IMerchantPayRegLogService merchantPayRegLogService;

    @Override
    public PageInfo<MerchantQueryRes> queryPage(MerchantQueryReq params) {
        final IPage<MerchantQueryRes> page = this.baseMapper.queryPage(new PageDTO<>(params.getCurrentPage(), params.getPageSize()), params);
        return new PageInfo<MerchantQueryRes>(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public MerchantAddStepOneNewRes addNew(MerchantAddReqNew params) {

        List<MerchantPayRegFileResVO> files = tradeApiClient.merchantUploadQuery(params.getFileIds());
        Asserts.isTrue(CollectionUtils.isNotEmpty(files), "请上传相关证件照！");
        if (params.getMerchantType().equals(3)) {
            idFileCheck(Arrays.asList(IdPhotoEnums.fr_sfz, IdPhotoEnums.fr_sfz_fm), files);
            // 小微商户
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.fzzmcl, files) || fileIsUpload(IdPhotoEnums.fzzmcl1, files), "小微商户至少上传一张辅助材料！");
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.zcsfz, files), "小微商户至少上传一张手持身份证自拍照");
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.snzp, files), "小微商户至少上传一张室内照");
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.wzapp, files), "小微商户至少上传一张网站或APP截图");
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.fzzmcl, files) || fileIsUpload(IdPhotoEnums.zlxy, files)
                    || fileIsUpload(IdPhotoEnums.cqzm, files) || fileIsUpload(IdPhotoEnums.yezzzz, files)
                    || fileIsUpload(IdPhotoEnums.dsfzm, files) || fileIsUpload(IdPhotoEnums.qtxwshzmcl, files), "小微商户至少上传一张辅助证明材料、租赁协议、产权证明、执业资质证照、第三方证明、其他小微商户证明材料");
        } else {
            if(params.getMerchantType().equals(2)){
                Asserts.isTrue(StringUtils.isNotEmpty(params.getLegalAddress()), "法人住所不允许为空！");
            }
            // 企业、个体户
            idFileCheck(Arrays.asList(IdPhotoEnums.fr_sfz, IdPhotoEnums.fr_sfz_fm, IdPhotoEnums.sh_yyzz), files);
            Asserts.isTrue(StringUtils.isNotEmpty(params.getShopLicenseBeginDate()) && StringUtils.isNotEmpty(params.getShopLicenseEndDate()), "企业、机关单位、个体商户营业执照有效期必传！");
            if (params.getMerchantType().equals(1)) {
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.khxkz, files), "企业商户必须上传开户许可证！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.wzapp, files), "企业商户必须上传至少一张网站或APP截图！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.mtzp, files), "企业商户必须上传至少一张门头照！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.snzp, files), "企业商户必须上传至少一张室内照片！");
            }
        }
        final Platform platform = platformService.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, params.getPlatformCode()));
        final List<Merchant> merchants = this.list(new LambdaQueryWrapper<Merchant>().eq(Merchant::getShopLic, params.getShopLic()));

        if (!CollectionUtils.isEmpty(merchants)) {
            // 商户已注册，判断商户有没有做过对应平台的进件
            final List<MerchantPayConfig> merchantPayConfigs = merchantPayConfigService.list(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getMerchantCode, merchants.get(0).getMerchantCode())
                    .eq(MerchantPayConfig::getPlatformPayChannelId, platform.getOrgPaymentChannelId()));
            long count = merchantPayConfigs.stream().filter(m -> !m.getMerchantStatus().equals(MerchantStatusEnums.delete.getCode())).count();
            Asserts.isTrue(count == 0, "该社会信用代码/小微商户身份证已有进件记录，请不要重复进件！");
        }

        return transactionTemplate.execute(transactionStatus -> {
            try {
                Merchant merchant = null;
                PlatformMerchant platformMerchant = null;
                if (CollectionUtils.isEmpty(merchants)) {
                    // 商户不存在，新建商户
                    merchant = MerchantConvert.INSTANCE.convert(params);
                    // 拼接creatTime时间戳(秒)后进行MD5运算 防止同名
                    merchant.setCreatedDt(LocalDateTime.now());
                    String content = merchant.getMerchantName() + String.valueOf(LocalDateTime.now()).substring(0, 19);
                    merchant.setMerchantCode(DigestUtils.md5DigestAsHex(content.getBytes()).toUpperCase());
                    merchant.setCreatedDt(LocalDateTime.now());
                    this.save(merchant);
                    // 保存商户关联平台
                    platformMerchant = new PlatformMerchant();
                    platformMerchant.setPlatformCode(platform.getPlatformCode());
                    platformMerchant.setMerchantCode(merchant.getMerchantCode());
                    platformMerchant.setMerchantRole(0);
                    platformMerchant.setCreatedDt(LocalDateTime.now());
                    platformMerchantService.save(platformMerchant);
                    // 保存证件信息
                    saveCerts(merchant, params, platform, files);
                } else {
                    // 商户已存在，但是进件银行不是一家
                    merchant = merchants.get(0);
                    // 保存商户关联平台
                    platformMerchant = new PlatformMerchant();
                    platformMerchant.setPlatformCode(platform.getPlatformCode());
                    platformMerchant.setMerchantCode(merchant.getMerchantCode());
                    platformMerchant.setMerchantRole(0);
                    platformMerchant.setCreatedDt(LocalDateTime.now());
                    platformMerchantService.save(platformMerchant);
                    // 保存证件信息
                    saveCerts(merchant, params, platform, files);
                }
                // 保存管理员信息
                MerchantAddSuperAdminReq superAdminReq = new MerchantAddSuperAdminReq();
                superAdminReq.setPlatformMerchantId(platformMerchant.getId());
                superAdminReq.setMerchantUserName(params.getMerchantName());
                superAdminReq.setUserId(params.getUserId());
                superAdminReq.setShopBusiness(params.getShopBusiness());
                superAdminReq.setPhone(params.getPhone());
                superAdminReq.setLogoUrl(params.getLogoUrl());
                addMerchantSuperAdmin(superAdminReq);
                if (null != params.getPlatformPercent()) {
                    // 保存结算信息
                    PlatformMerchantSettleRule rule = new PlatformMerchantSettleRule();
                    rule.setCycleType("T");
                    rule.setPlatformPercent(params.getPlatformPercent());
                    rule.setPlatformMerchantId(platformMerchant.getId());
                    rule.setCycleValue(1);
                    rule.setRemark("默认规则T+1清分");
                    rule.setOrgPaymentChannelId(platform.getOrgPaymentChannelId());
                    addSettlement(rule);
                }
                submitMerchant2UserCenter(merchant, platformMerchant, params.getXToken());
                return queryByMerchantAndPlatformNew(platform, merchant);
            } catch (Exception e) {
                transactionStatus.setRollbackOnly();
                throw e;
            }
        });
    }


    private void idFileCheck(List<IdPhotoEnums> enums, List<MerchantPayRegFileResVO> files) {
        for (IdPhotoEnums anEnum : enums) {
            Asserts.isTrue(fileIsUpload(anEnum, files), "请上传" + anEnum.getName() + "!");
        }
    }

    private boolean fileIsUpload(IdPhotoEnums anEnum, List<MerchantPayRegFileResVO> files) {
        return files.stream().anyMatch(f -> StringUtils.isNotEmpty(f.getDocumentType()) && anEnum.getCode().equals(f.getDocumentType()));
    }

    @Override
    public MerchantAddStepOneRes queryByShopLic(String platformCode, String shopLic) {
        final Platform platform = platformService.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformCode));
        Asserts.isTrue(Objects.nonNull(platform), "未查询到平台信息！");
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getShopLic, shopLic));
        return queryByMerchantAndPlatform(platform, merchant);
    }

    @Override
    public void addMerchantSuperAdmin(MerchantAddSuperAdminReq params) {
        PlatformMerchantUser platformMerchantUser = new PlatformMerchantUser();
        platformMerchantUser.setMerchantUserName(params.getMerchantUserName());
        platformMerchantUser.setPlatformMerchantId(params.getPlatformMerchantId());
        platformMerchantUser.setUserId(params.getUserId());
        platformMerchantUser.setIsSuperAdmin(1);
        platformMerchantUser.setUserStatus(1);
        platformMerchantUser.setPhone(params.getPhone());
        platformMerchantUser.setLogoUrl(params.getLogoUrl());
        platformMerchantUserService.addSuperAdmin(platformMerchantUser);
    }

    @Override
    public void addSettlement(PlatformMerchantSettleRule rule) {
        platformMerchantSettleRuleService.addRule(rule);
    }

    @Override
    public Merchant getByMerchantCode(String merchantCode) {
        return this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, merchantCode));
    }

    @Override
    public PlatformMerchantBaseInfoRes queryMerchantBaseInfo(Long platformMerchantId) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(platformMerchantId);
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Merchant merchant = this.getByMerchantCode(platformMerchant.getMerchantCode());
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        // 平台基础信息
        final MerchantAddStepOneRes merchantAddStepOneRes = queryByMerchantAndPlatform(platform, merchant);
        return MerchantConvert.INSTANCE.convert2PlatformMerchantDetailRes(merchantAddStepOneRes);
    }

    @Override
    public PlatformMerchantBusinessInfoRes queryMerchantBusinessInfo(Long platformMerchantId) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(platformMerchantId);
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        // 更新开户行信息
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        PlatformMerchantBusinessInfoRes res = new PlatformMerchantBusinessInfoRes();
        res.setTradeMerchantCode(payConfig.getTradeMerchantCode());
        res.setTradeChannelCode(payConfig.getTradeChannelCode());
        res.setTradeChannelName(payConfig.getTradeChannelName());
        res.setQr(payConfig.getQr());
        res.setMerchantStatus(payConfig.getMerchantStatus());
        res.setMerchantStatusDescribe(payConfig.getMerchantStatusDescribe());
        res.setPlatformMerchantId(platformMerchant.getId());
        res.setShopBusiness(payConfig.getShopBusiness());
        res.setBankAcctName(payConfig.getBankAcctName());
        res.setBankNo(payConfig.getBankNo());
        res.setBankAcctPhone(payConfig.getBankAcctPhone());
        res.setMccCode(payConfig.getMccCode());
        res.setMerchantRegStatus(payConfig.getMerchantRegStatus());
        // 提现银行卡正面、反面
        List<MerchantPayCert> payCerts = merchantPayCertService.list(new LambdaQueryWrapper<MerchantPayCert>().eq(MerchantPayCert::getMerchantPayConfigId, payConfig.getId()).in(MerchantPayCert::getCertType, Arrays.asList(IdPhotoEnums.yhk_zmz.getCode(), IdPhotoEnums.yhk_bmz.getCode())));
        for (MerchantPayCert payCert : payCerts) {
            if (payCert.getCertType().equals(IdPhotoEnums.yhk_zmz.getCode())) {
                res.setBankCardPositiveUrl(payCert.getInnerFilePath());
            } else {
                res.setBankCardBackUrl(payCert.getInnerFilePath());
            }
        }
        // 清分规则信息
        List<PlatformMerchantSettleRule> ruleList = platformMerchantSettleRuleService.list(new LambdaQueryWrapper<PlatformMerchantSettleRule>().eq(PlatformMerchantSettleRule::getPlatformMerchantId, platformMerchant.getId()).eq(PlatformMerchantSettleRule::getRuleStatus, 1));
        if (!CollectionUtils.isEmpty(ruleList)) {
            res.setRuleCode(ruleList.get(0).getRuleCode());
            res.setPlatformPercent(ruleList.get(0).getPlatformPercent());
            res.setCycleType(ruleList.get(0).getCycleType());
            res.setCycleValue(ruleList.get(0).getCycleValue());
            res.setClearRemark(ruleList.get(0).getRemark());
        }
        // 管理员信息
        final PlatformMerchantUserDetailDTO platformMerchantUser = platformMerchantUserService.queryPlatformMerchantSuperAdmin(platformMerchant.getId());
        res.setMerchantSuperAdmin(platformMerchantUser);
        // 补全行业信息
        setMccName(res);
        return res;
    }

    @Override
    public void updateSettlement(MerchantUpdateSettlReq params) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        PlatformMerchantSettleRule rule = new PlatformMerchantSettleRule();
        rule.setPlatformMerchantId(params.getPlatformMerchantId());
        rule.setPlatformPercent(params.getPlatformPercent());
        rule.setCycleType("T");
        rule.setCycleValue(1);
        rule.setRemark("默认规则T+1");
        rule.setOrgPaymentChannelId(platform.getOrgPaymentChannelId());

        MerchantPayConfig merchantPayConfig = merchantPayConfigService.getOne(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getMerchantCode, platformMerchant.getMerchantCode()));
        transactionTemplate.execute(transactionStatus -> {
            try {
                final PlatformMerchantSettleRule settleRule = platformMerchantSettleRuleService.currentRule(params.getPlatformMerchantId());
                if (Objects.nonNull(settleRule)) {
                    platformMerchantSettleRuleService.deactivateSettlement(settleRule.getRuleCode());
                }
                // 推送到交易中台
                if (StringUtils.isNotEmpty(merchantPayConfig.getTradeMerchantCode())) {
                    MerchantPayRegSettleRuleReqVO settle = new MerchantPayRegSettleRuleReqVO();
                    settle.setMerchantCode(merchantPayConfig.getTradeMerchantCode());
                    settle.setPlatformPercent(rule.getPlatformPercent());
                    settle.setCycleType(rule.getCycleType());
                    settle.setCycleValue(rule.getCycleValue().toString());
                    tradeApiClient.setMerchantSettleRule(settle);
                }
                platformMerchantSettleRuleService.addRule(rule);
                return true;
            } catch (Exception e) {
                transactionStatus.setRollbackOnly();
                throw e;
            }
        });
    }

    @Override
    public void deactivateSettlement(Long platformMerchantId) {
        final PlatformMerchantSettleRule settleRule = platformMerchantSettleRuleService.currentRule(platformMerchantId);
        if (Objects.nonNull(settleRule)) {
            platformMerchantSettleRuleService.deactivateSettlement(settleRule.getRuleCode());
        }
    }

    @Override
    public void addSettlementRule(MerchantAddSettlRuleReq params) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        // 保存清分规则信息
        PlatformMerchantSettleRule rule = new PlatformMerchantSettleRule();
        rule.setCycleType("T");
        rule.setPlatformMerchantId(platformMerchant.getId());
        rule.setCycleValue(1);
        rule.setRemark(params.getClearRemark());
        rule.setOrgPaymentChannelId(platform.getOrgPaymentChannelId());

        // 推送到交易中台
        MerchantPayConfig merchantPayConfig = merchantPayConfigService.getOne(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getMerchantCode, platformMerchant.getMerchantCode()));
        MerchantPayRegSettleRuleReqVO settle = new MerchantPayRegSettleRuleReqVO();
        settle.setMerchantCode(merchantPayConfig.getTradeMerchantCode());
        settle.setPlatformPercent(rule.getPlatformPercent());
        settle.setCycleType(rule.getCycleType());
        settle.setCycleValue(rule.getCycleValue().toString());
        tradeApiClient.setMerchantSettleRule(settle);
        platformMerchantSettleRuleService.addRule(rule);
    }

    @Override
    public void setMerchantStatusNew(MerchantStatusSetReq params) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        // 更新开户行信息
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        if (params.getMerchantStatus().equals(payConfig.getMerchantStatus())) {
            return;
        }
        Optional<MerchantStatusEnums> statusEnums = MerchantStatusEnums.getByCode(params.getMerchantStatus());
        Asserts.isTrue(statusEnums.isPresent(), "不支持的商户状态！");
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, payConfig.getMerchantCode()));
        MerchantPayConfig updateMerchantPay = new MerchantPayConfig();
        if (params.getMerchantStatus().equals(MerchantStatusEnums.stop.getCode())) {
            // 源状态==2可停用
            Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.normal.getCode()), "当前状态不允许停用！");
            updateMerchantPay.setMerchantStatus(params.getMerchantStatus());
            updateMerchantPay.setMerchantStatusDescribe(MerchantStatusEnums.stop.getName());
        } else if (params.getMerchantStatus().equals(MerchantStatusEnums.normal.getCode())) {
            // 源状态==2时可启用
            Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.stop.getCode()), "当前状态不允许恢复！");
            updateMerchantPay.setMerchantStatus(params.getMerchantStatus());
            updateMerchantPay.setMerchantStatusDescribe(MerchantStatusEnums.normal.getName());
        } else if (params.getMerchantStatus().equals(MerchantStatusEnums.platform_pass.getCode())) {
            // 源状态==0时可审批通过
            Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.init.getCode()), "当前状态不允许审核通过！");
            // 平台审核通过，将商户信息和用户信息注册到交易中台和用户中台
            submitMerchant2TradeNew(payConfig, platformMerchant, merchant, params.getXToken());
            updateMerchantPay.setMerchantStatusDescribe(MerchantStatusEnums.platform_pass.getName());
            sendSysMsg(merchant.getMerchantCode(), "平台审核通过", "平台审核通过，等待银行审核！平台审核通过时间:" + DateTimeUtil.formatter(LocalDateTime.now(), DateTimeUtil.bj_pattern), params.getXToken());
        } else if (params.getMerchantStatus().equals(MerchantStatusEnums.platform_not_pass.getCode())) {
            // 源状态==0时可审批不通过
            Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.init.getCode()), "当前状态不允许审核不通过！");
            Asserts.isTrue(StringUtils.isNotEmpty(params.getMerchantStatusDescribe()), "请输入审核不通过原因！");
            updateMerchantPay.setMerchantStatus(params.getMerchantStatus());
            updateMerchantPay.setMerchantStatusDescribe(MerchantStatusEnums.platform_not_pass.getName());
            //submitMerchant2UserCenter(merchant, platformMerchant, params.getXToken());
            sendSysMsg(payConfig.getMerchantCode(), "平台审核不通过，请查看具体原因进行处理", "平台审核不通过！备注【" + Optional.ofNullable(params.getMerchantStatusDescribe()).orElse("")
                    + "】，平台审核时间:" + DateTimeUtil.formatter(LocalDateTime.now(), DateTimeUtil.bj_pattern), params.getXToken());
        } else {
            Asserts.fail("不允许设置该状态！");
        }
        // 修改状态
        updateMerchantPay.setId(payConfig.getId());
        if (StringUtils.isNotEmpty(params.getMerchantStatusDescribe())) {
            updateMerchantPay.setMerchantStatusDescribe(params.getMerchantStatusDescribe());
        }
        updateMerchantPay.setLastUpdDt(LocalDateTime.now());
        merchantPayConfigService.updateById(updateMerchantPay);
        // 清空缓存的支付商户信息
        TradeCache.removeTreadMerchant(platformMerchant.getId());
    }

    /**
     * 发送系统消息
     *
     * @param merchantCode
     */
    private void sendSysMsg(String merchantCode, String title, String msg, String xToken) {
        Map<String, String> params = new HashMap<>();
        params.put("id", merchantCode);

        try {
            String result = tcFeignClient.getOrgUsers(params, xToken);
            log.info("查询商户管理员列表返回: {}, 返回: {}", JSON.toJSONString(result), result);
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") == 200) {
                JSONArray userList = jsonObject.getJSONArray("result");
                if (null != userList && userList.size() > 0) {
                    StringBuilder ids = new StringBuilder();
                    for (int i = 0; i < userList.size(); i++) {
                        JSONObject object = JSON.parseObject(JSON.toJSONString(userList.get(i)));
                        String id = object.getString("id");
                        if (StringUtils.isNotEmpty(id)) {
                            ids.append(id);
                            if (i != userList.size() - 1) {
                                ids.append(",");
                            }
                        }
                    }

                    String r = tcFeignClient.SendSysMsg(new SysMessageRequest(ids.toString(), title, msg), xToken);
                    log.info("消息推送,title:{},ids:{},message:{},结果：{}", title, ids, msg, r);
                }
            }
        } catch (Exception e) {
            log.error("推送系统消息异常:", e);
        }
    }

    /**
     * 提交商户信息到交易中心、商户中心
     *
     * @param payConfig 平台商户id
     */
    private void submitMerchant2TradeNew(MerchantPayConfig payConfig, PlatformMerchant platformMerchant, Merchant merchant, String xToken) {
        //submitMerchant2UserCenter(merchant, platformMerchant, xToken);
        RegisterMerchantReqNewVO registerMerchantReqVO = new RegisterMerchantReqNewVO();
        registerMerchantReqVO.setMerchantType(merchant.getMerchantType());
        registerMerchantReqVO.setMerchantName(merchant.getMerchantName());
        registerMerchantReqVO.setShopLic(merchant.getShopLic());
        registerMerchantReqVO.setShopProvinceId(payConfig.getShopProvinceId());
        registerMerchantReqVO.setShopCityId(payConfig.getShopCityId());
        registerMerchantReqVO.setShopCountryId(payConfig.getShopCountryId());
        registerMerchantReqVO.setShopAddress(payConfig.getShopAddress());
        registerMerchantReqVO.setShopLicenseBeginDate(payConfig.getShopLicenseBeginDate());
        registerMerchantReqVO.setShopLicenseEndDate(payConfig.getShopLicenseEndDate());
        registerMerchantReqVO.setLegalName(merchant.getLegalName());
        registerMerchantReqVO.setLegalIdcardNo(merchant.getLegalIdcardNo());
        registerMerchantReqVO.setLegalSex(merchant.getLegalSex());
        registerMerchantReqVO.setLegalMobile(merchant.getLegalMobile());
        registerMerchantReqVO.setLegalCardBeginDate(merchant.getLegalCardBeginDate());
        registerMerchantReqVO.setLegalCardDeadline(merchant.getLegalCardDeadline());
        registerMerchantReqVO.setLegalAddress(merchant.getLegalAddress());
        registerMerchantReqVO.setMccCode(payConfig.getMccCode());
        registerMerchantReqVO.setTradeMerchantPayRegId(payConfig.getTradeMerchantPayRegId());

        final List<MerchantPayCert> files = merchantPayCertService.list(new LambdaQueryWrapper<MerchantPayCert>().eq(MerchantPayCert::getMerchantPayConfigId, payConfig.getId()));
        registerMerchantReqVO.setFileIds(files.stream().map(MerchantPayCert::getFileId).toList());
        registerMerchantReqVO.setLegalOccupation(merchant.getLegalOccupation());
        registerMerchantReqVO.setShopBusiness(payConfig.getShopBusiness());
        registerMerchantReqVO.setBankNo(payConfig.getBankNo());
        registerMerchantReqVO.setBankAcctNo(payConfig.getBankAcctNo());
        registerMerchantReqVO.setBankAcctName(payConfig.getBankAcctName());
        registerMerchantReqVO.setBankAcctPhone(payConfig.getBankAcctPhone());

        final PlatformMerchantSettleRule rule = platformMerchantSettleRuleService.currentRule(platformMerchant.getId());
        Asserts.isNotNull(rule, "请设置抽佣比列！");
        registerMerchantReqVO.setPlatformPercent(rule.getPlatformPercent());
        registerMerchantReqVO.setCycleType(rule.getCycleType());
        registerMerchantReqVO.setCycleValue(rule.getCycleValue());
        registerMerchantReqVO.setClearRemark(rule.getRemark());
        // 公司账户
        registerMerchantReqVO.setBankAcctType("1");
        if (merchant.getMerchantType().equals(3)) {
            // 个人账户
            registerMerchantReqVO.setBankAcctType("0");
        }
        registerMerchantReqVO.setNotifyUrl(miniAppProperties.getNotifyUrl() + "notify/merchantCallback");
        final MerchantRegAllInfoNewRes merchantRegAllInfoRes = tradeApiClient.registerMerchantNew(registerMerchantReqVO);
        Asserts.isNotNull(merchantRegAllInfoRes, "提交进件材料失败！");
        //更新商户进件-交易商户信息
        MerchantTradeUpdateDTO updateDTO = new MerchantTradeUpdateDTO();
        updateDTO.setMerchantCode(merchant.getMerchantCode());
        updateDTO.setPlatformPayChannelId(merchantRegAllInfoRes.getOrgPaymentChannelId());
        updateDTO.setTradeMerchantCode(merchantRegAllInfoRes.getTradeMerchantCode());
        updateDTO.setTradeMerchantPayRegId(merchantRegAllInfoRes.getTradeMerchantPayRegId());
        updateDTO.setRegCurrentFlows(merchantRegAllInfoRes.getRegCurrentFlows());
        updateDTO.setRegNextFlows(merchantRegAllInfoRes.getRegNextFlows());
        merchantPayConfigService.setTradeInfo(updateDTO);
        //merchantPayRegLogService.saveFlowLog(payConfig.getId(), MerchantRegFlowsEnums.COMPLEX_UPLOAD, MerchantRegFlowsEnums.UPLOAD_FILE, 1);
    }

    /**
     * 提交商户信息到用户中心
     */
    private void submitMerchant2UserCenter(Merchant merchant, PlatformMerchant platformMerchant, String xToken) {
        final PlatformMerchantUserDetailDTO admin = platformMerchantUserService.queryPlatformMerchantSuperAdmin(platformMerchant.getId());
        // TODO 调用用户中台注册商户和管理员
        SyncSaveMerchantInfoRequest syncRequest = SyncSaveMerchantInfoRequest.builder()
                .phoneNumber(admin.getPhone())
                .businessUnitName(merchant.getMerchantName())
                .businessUnitID(merchant.getMerchantCode())
                .userName(admin.getMerchantUserName())
                .sex(0)
                .userID(admin.getUserId())
                .tradeID(merchantTag)
                .build();
        String result = tcFeignClient.saveEnterpriseInfoHotel(syncRequest, xToken);
        Asserts.isTrue(StringUtils.isNotEmpty(result), "用户中心更换管理员失败！");
        JSONObject jsonObject = JSON.parseObject(result);
        log.info("同步注册商户账号完成，请求: {}, 返回: {}", JSON.toJSONString(syncRequest), result);
        Asserts.isTrue(null != jsonObject && jsonObject.containsKey("Code") && jsonObject.getInteger("Code") == 200, "商户中心注册商户失败！");

    }

    private String getFileUrlByType(List<MerchantPayCert> files, IdPhotoEnums enums) {
        if (!CollectionUtils.isEmpty(files)) {
            return files.stream().filter(f -> f.getCertType().equals(enums.getCode())).findFirst().map(MerchantPayCert::getInnerFilePath).orElse("");
        }
        return null;
    }

    @Transactional
    @Override
    public PlatformMerchantUserDetailDTO changeMerchantAdmin(SetMerchantAdminReq params) {
        PlatformMerchantUser oldUser = platformMerchantUserService.getOne(new LambdaQueryWrapper<PlatformMerchantUser>().eq(PlatformMerchantUser::getUserId, params.getOldUserId())
                .eq(PlatformMerchantUser::getPlatformMerchantId, params.getPlatformMerchantId()));
        Asserts.isTrue(Objects.nonNull(oldUser), "用户不存在！");
        List<PlatformMerchantUser> users = platformMerchantUserService.list(new LambdaQueryWrapper<PlatformMerchantUser>().eq(PlatformMerchantUser::getPlatformMerchantId, params.getPlatformMerchantId()));
        boolean newAdminExist = false;
        if (!CollectionUtils.isEmpty(users)) {
            for (PlatformMerchantUser platformMerchantUser : users) {
                if (platformMerchantUser.getUserId().equals(params.getNewUserId())) {
                    platformMerchantUser.setIsSuperAdmin(1);
                    newAdminExist = true;
                } else {
                    platformMerchantUser.setIsSuperAdmin(0);
                }
                platformMerchantUser.setUserStatus(1);
                platformMerchantUser.setLastUpdDt(LocalDateTime.now());
            }
            platformMerchantUserService.updateBatchById(users);
        }
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        // 调用用户中心更换默认管理员
        ChangeOrgManagerDTO changeOrgManagerDTO = new ChangeOrgManagerDTO(params.getOldUserId(), params.getNewUserId(), platformMerchant.getMerchantCode(), "87561");
        String result = tcFeignClient.ChangeOrgManager(changeOrgManagerDTO, params.getXToke());
        Asserts.isTrue(StringUtils.isNotEmpty(result), "用户中心更换管理员失败！");
        JSONObject jsonObject = JSON.parseObject(result);
        Asserts.isTrue(jsonObject.getInteger("code") == 200, jsonObject.getString("message"));
        if (!newAdminExist) {
            // 保存新管理员
            MerchantAddSuperAdminReq superAdminReq = new MerchantAddSuperAdminReq();
            superAdminReq.setPlatformMerchantId(platformMerchant.getId());
            superAdminReq.setMerchantUserName(params.getMerchantUserName());
            superAdminReq.setUserId(params.getNewUserId());
            superAdminReq.setShopBusiness("");
            superAdminReq.setPhone(params.getPhoneNumber());
            superAdminReq.setLogoUrl("");
            addMerchantSuperAdmin(superAdminReq);
        }
        log.info("调用用户中心更换管理员，请求params：{}，返回：{}", JsonUtil.toJsonString(changeOrgManagerDTO), result);
        return platformMerchantUserService.queryPlatformMerchantSuperAdmin(params.getPlatformMerchantId());
    }

    @Override
    public void updateMerchantInfoNew(MerchantUpdateNewReq params) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        List<MerchantPayRegFileResVO> files = tradeApiClient.merchantUploadQuery(params.getFileIds());
        Asserts.isTrue(CollectionUtils.isNotEmpty(files), "请上传相关证件照！");
        if (params.getMerchantType().equals(3)) {
            idFileCheck(Arrays.asList(IdPhotoEnums.fr_sfz, IdPhotoEnums.fr_sfz_fm), files);
            // 小微商户
            Asserts.isTrue(fileIsUpload(IdPhotoEnums.fzzmcl, files) || fileIsUpload(IdPhotoEnums.fzzmcl1, files), "小微商户至少上传一张辅助材料！");
        } else {
            // 企业、个体户
            idFileCheck(Arrays.asList(IdPhotoEnums.fr_sfz, IdPhotoEnums.fr_sfz_fm, IdPhotoEnums.sh_yyzz), files);
            Asserts.isTrue(StringUtils.isNotEmpty(params.getShopLicenseBeginDate()) && StringUtils.isNotEmpty(params.getShopLicenseEndDate()), "企业、机关单位、个体商户营业执照有效期必传！");
            if (params.getMerchantType().equals(1)) {
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.khxkz, files), "企业商户必须上传开户许可证！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.wzapp, files), "企业商户必须上传至少一张网站或APP截图！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.mtzp, files), "企业商户必须上传至少一张门头照！");
                Asserts.isTrue(fileIsUpload(IdPhotoEnums.snzp, files), "企业商户必须上传至少一张室内照片！");
            }
        }
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        // 查询商户进件信息
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        Asserts.isTrue(null != payConfig, "商户进件记录不存在！");
        Asserts.isTrue(!payConfig.getMerchantStatus().equals(MerchantStatusEnums.stop.getCode()), "商户已停用，不允许修改！");
        Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.init.getCode()) ||
                (payConfig.getMerchantStatus() >= MerchantStatusEnums.platform_not_pass.getCode() && payConfig.getMerchantStatus() <= MerchantStatusEnums.bank_material_supplement.getCode()), "商户当前状态不允许编辑！");
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, platformMerchant.getMerchantCode()));
        final Boolean execute = transactionTemplate.execute(transactionStatus -> {
            try {
                // 等待平台审核、平台审核不通过，此时商户材料还没有提交到交易系统、用户系统
                // 只做信息的更新
                // 1、更新商户信息
                Merchant updateMerchant = MerchantConvert.INSTANCE.convertMerchantUpdateReq(params);
                updateMerchant.setId(merchant.getId());
                updateMerchant.setLastUpdDt(LocalDateTime.now());
                this.updateById(updateMerchant);
                // 2、更新进件信息
                final MerchantPayConfig updateMerchantPay = MerchantConvert.INSTANCE.convertFromMerchantUpdateReq(params);
                updateMerchantPay.setId(payConfig.getId());
                updateMerchantPay.setMerchantCode(merchant.getMerchantCode());
                updateMerchantPay.setCreatedDt(LocalDateTime.now());
                updateMerchantPay.setPlatformPayChannelId(platform.getOrgPaymentChannelId());
                updateMerchantPay.setShopBusiness(params.getShopBusiness());
                updateMerchantPay.setBankAcctType(merchant.getMerchantType().equals(3) ? 0 : 1);
                updateMerchantPay.setBankAcctNo(params.getBankAcctNo());
                updateMerchantPay.setBankNo(params.getBankNo());
                updateMerchantPay.setBankAcctName(params.getBankAcctName());
                updateMerchantPay.setBankAcctPhone(params.getBankAcctPhone());
                // 将状态重置为待审核
                updateMerchantPay.setMerchantStatus(MerchantStatusEnums.init.getCode());
                updateMerchantPay.setMerchantRegStatus(MerchantRegStatusEnums.INIT.getCode());
                updateMerchantPay.setRegCurrentFlows(MerchantRegStatusEnums.INIT.getCode());
                updateMerchantPay.setRegNextFlows(MerchantRegStatusEnums.INIT.getCode());
                merchantPayConfigService.updateById(updateMerchantPay);

                // 3、进件证件照信息
                // 保存证件照信息
                final List<MerchantPayCert> merchantPayCerts = new ArrayList<>(files.size());
                for (MerchantPayRegFileResVO file : files) {
                    MerchantPayCert merchantPayCert = new MerchantPayCert();
                    merchantPayCert.setFileId(file.getId().toString());
                    merchantPayCert.setCreatedDt(LocalDateTime.now());
                    merchantPayCert.setMerchantPayConfigId(payConfig.getId());
                    merchantPayCert.setCertType(file.getDocumentType());
                    merchantPayCert.setCertName(file.getFileName());
                    merchantPayCert.setFilePath(file.getInnerFilePath());
                    merchantPayCert.setInnerFilePath(file.getInnerFilePath());
                    merchantPayCert.setCreatedDt(LocalDateTime.now());
                    merchantPayCerts.add(merchantPayCert);
                }
                merchantPayCertService.remove(new LambdaQueryWrapper<MerchantPayCert>().eq(MerchantPayCert::getMerchantPayConfigId, payConfig.getId()));
                merchantPayCertService.saveBatch(merchantPayCerts);
                // 4、管理员处理
                platformMerchantUserService.removeMerchantSuperAdmin(platformMerchant.getId());
                // 保存管理员信息
                MerchantAddSuperAdminReq superAdminReq = new MerchantAddSuperAdminReq();
                superAdminReq.setPlatformMerchantId(platformMerchant.getId());
                superAdminReq.setMerchantUserName(params.getMerchantName());
                superAdminReq.setUserId(params.getUserId());
                superAdminReq.setShopBusiness(params.getShopBusiness());
                superAdminReq.setPhone(params.getPhone());
                superAdminReq.setLogoUrl(params.getLogoUrl());
                addMerchantSuperAdmin(superAdminReq);

                // 更新清分规则
                    /*MerchantUpdateSettlReq merchantUpdateSettlReq = new MerchantUpdateSettlReq();
                    merchantUpdateSettlReq.setPlatformMerchantId(platformMerchant.getId());
                    merchantUpdateSettlReq.setPlatformPercent(params.getPlatformPercent());
                    updateSettlement(merchantUpdateSettlReq);*/
                return true;
            } catch (Exception e) {
                transactionStatus.setRollbackOnly();
                throw e;
            }
        });

    }

    @Override
    public void merchantStatusChangeNotify(TradeMerchantStatusReq merchantStatusReq) {
        final List<MerchantPayConfig> list = merchantPayConfigService.list(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getTradeMerchantCode, merchantStatusReq.getTradeMerchantCode()));
        if (CollectionUtils.isEmpty(list)) {
            log.warn("未查询到商户进件记录！");
            return;
        }
        final List<PlatformMerchant> platformMerchants = platformMerchantService.list(new LambdaQueryWrapper<PlatformMerchant>().in(PlatformMerchant::getMerchantCode, list.stream().map(MerchantPayConfig::getMerchantCode).collect(Collectors.toList())));
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, platformMerchants.get(0).getMerchantCode()));
        // 更新状态
        final List<MerchantPayQr> merchantPayQrs = new ArrayList<>();
        // 判断是否是银行审核通过，审核通过生成商户收款码

        final Boolean success = transactionTemplate.execute(transactionStatus -> {
            try {
                final List<MerchantPayConfig> merchantPayConfigs = new ArrayList<>();
                for (PlatformMerchant platformMerchant : platformMerchants) {
                    list.stream().filter(mpc -> mpc.getMerchantCode().equals(platformMerchant.getMerchantCode())).forEach(mpc -> {
                        final MerchantPayConfig updateMerchant = new MerchantPayConfig();
                        updateMerchant.setId(mpc.getId());
                        if (merchantStatusReq.getTradeMerchantStatus().equals(MerchantApplyStatusEnums.success.getCode())) {
                            updateMerchant.setMerchantStatus(MerchantStatusEnums.normal.getCode());
                            if (StringUtils.isEmpty(mpc.getQr())) {
                                // 生成商户的收款码
                                String qrHost = miniAppProperties.getQrHost();
                                qrHost += ("?platformCode=" + platformMerchants.get(0).getPlatformCode() + "&platformMerchantId=" + platformMerchant.getId());
                                final byte[] codeImage = QRCodeGenerator.generateQRCodeImage(qrHost, 300, 300);
                                Asserts.isNotNull(codeImage, "生成商户收款码异常!");
                                final MinioUploadDto minioUploadDto = uploadService.minioUploadImg(merchant.getMerchantName() + "聚合收款码.png", codeImage);
                                Asserts.isNotNull(minioUploadDto, "上传商户收款码异常!");
                                updateMerchant.setQr(minioUploadDto.getUrl());

                                final MerchantPayQr merchantPayQr = new MerchantPayQr();
                                merchantPayQr.setMerchantPayConfigId(mpc.getId());
                                merchantPayQr.setPlatformCode(platformMerchants.get(0).getPlatformCode());
                                merchantPayQr.setQr(minioUploadDto.getUrl());
                                merchantPayQr.setQrStatus(0);
                                merchantPayQr.setCreatedDt(LocalDateTime.now());
                                merchantPayQr.setQrContent(qrHost);
                                merchantPayQrs.add(merchantPayQr);
                            }

                        } else if (merchantStatusReq.getTradeMerchantStatus().equals(MerchantApplyStatusEnums.final_error.getMsg())) {
                            // 商户进件失败，将状态置为
                            //updateMerchant.setMerchantStatus(merchantStatusReq.getTradeMerchantStatus());
                            updateMerchant.setMerchantStatus(MerchantStatusEnums.bank_material_supplement.getCode());
                            updateMerchant.setMerchantRegStatus(MerchantRegStatusEnums.PROCESS_CANCEL.getCode());
                            updateMerchant.setRegCurrentFlows(MerchantRegStatusEnums.INIT.getCode());
                            updateMerchant.setRegNextFlows(MerchantRegStatusEnums.INIT.getCode());
                            updateMerchant.setLastUpdDt(LocalDateTime.now());
                            // 清空商户状态缓存
                            TradeCache.getTreadMerchant(mpc.getId());
                        } else if (merchantStatusReq.getTradeMerchantStatus().equals(MerchantApplyStatusEnums.ing.getCode())) {
                            // 商户进件失败，将状态置为
                            //updateMerchant.setMerchantStatus(merchantStatusReq.getTradeMerchantStatus());
                            //updateMerchant.setMerchantStatus(MerchantStatusEnums.platform_pass.getCode());
                            // 清空商户状态缓存
                        } else if (merchantStatusReq.getTradeMerchantStatus().equals(MerchantApplyStatusEnums.exception.getCode())) {
                            // 异常，前端状态显示：进件信息待补充（具体的异常信息）
                            updateMerchant.setMerchantStatus(MerchantStatusEnums.bank_material_supplement.getCode());
                            updateMerchant.setMerchantRegStatus(MerchantRegStatusEnums.INIT.getCode());
                            updateMerchant.setRegCurrentFlows(MerchantRegStatusEnums.INIT.getCode());
                            updateMerchant.setRegNextFlows(MerchantRegStatusEnums.INIT.getCode());
                            MerchantApplySubStatusEnums subStatusEnums = MerchantApplySubStatusEnums.getByCode(merchantStatusReq.getTradeMerchantSubStatus()).get();
                            if (subStatusEnums == MerchantApplySubStatusEnums.zlyz_yc) {
                                // 资料验证异常
                                updateMerchant.setMerchantRegStatus(MerchantRegStatusEnums.CERTIFICATE_VERIFICATION_FAILED.getCode());
                            } else if (subStatusEnums == MerchantApplySubStatusEnums.dgzh_yc) {
                                // 对公账户待验证或异常
                                updateMerchant.setMerchantRegStatus(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION.getCode());
                                updateMerchant.setRegCurrentFlows(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION.getCode());
                                updateMerchant.setRegNextFlows(MerchantRegStatusEnums.SIGNING_IN_PROGRESS.getCode());
                            } else if (subStatusEnums == MerchantApplySubStatusEnums.other) {
                                // 对公账户待验证或异常
                                updateMerchant.setMerchantRegStatus(MerchantRegStatusEnums.PROCESS_CANCEL.getCode());
                            }
                            updateMerchant.setLastUpdDt(LocalDateTime.now());
                        }
                        updateMerchant.setLastUpdDt(LocalDateTime.now());
                        merchantPayConfigs.add(updateMerchant);
                    });
                }
                if (CollectionUtils.isNotEmpty(merchantPayQrs)) {
                    merchantPayQrService.batchGenQr(merchantPayQrs);
                }
                if (CollectionUtils.isNotEmpty(merchantPayConfigs)) {
                    merchantPayConfigService.updateBatchById(merchantPayConfigs);
                }
                return true;
            } catch (Exception e) {
                throw e;
            }
        });
        Asserts.isTrue(null != success && success, "商户状态处理异常！");
    }

    @Override
    public PayMerchantDTO queryPayMerchant(Long platformMerchantId) {
        Optional<PayMerchantDTO> treadMerchant = TradeCache.getTreadMerchant(platformMerchantId);
        if (treadMerchant.isPresent()) {
            return treadMerchant.get();
        }
        final PayMerchantDTO payMerchantDTO = getBaseMapper().queryPayMerchant(platformMerchantId);
        Asserts.isTrue(Objects.nonNull(payMerchantDTO) && StringUtils.isNotEmpty(payMerchantDTO.getClientId()), "未读取到有效的商户信息！");
        TradeCache.cacheTreadMerchant(platformMerchantId, payMerchantDTO);
        return payMerchantDTO;
    }

    @Override
    public PayMerchantDTO queryPayMerchantByCode(String merchantCode) {
        //TODO 这里以后sass话要改，需要根据platform_code和merchant_code 来查询
        List<PlatformMerchant> list = platformMerchantService.list(new LambdaQueryWrapper<PlatformMerchant>().eq(PlatformMerchant::getMerchantCode, merchantCode));
        if (CollectionUtils.isNotEmpty(list)) {
            return queryPayMerchant(list.get(0).getId());
        }
        return null;
    }

    @Override
    public QueryCurrentMerchantRes currentMerchant(String merchantCode) {
        PayMerchantDTO payMerchantDTO = queryPayMerchantByCode(merchantCode);
        if (null != payMerchantDTO) {
            QueryCurrentMerchantRes currentMerchantRes = new QueryCurrentMerchantRes();
            currentMerchantRes.setMerchantCode(payMerchantDTO.getMerchantCode());
            currentMerchantRes.setMerchantName(payMerchantDTO.getMerchantName());
            currentMerchantRes.setPlatformMerchantId(payMerchantDTO.getPlatformMerchantId());
            //currentMerchantRes.setQr(payMerchantDTO.getQr());
            currentMerchantRes.setMerchantStatus(payMerchantDTO.getMerchantStatus());
            currentMerchantRes.setMerchantStatusDescribe(payMerchantDTO.getMerchantStatusDescribe());
            currentMerchantRes.setQr(payMerchantDTO.getQr());

            final PlatformMerchantSettleRule settleRule = platformMerchantSettleRuleService.currentRule(payMerchantDTO.getPlatformMerchantId());
            if (null != settleRule) {
                currentMerchantRes.setPlatformPercent(settleRule.getPlatformPercent());
            }
            currentMerchantRes.setAdminUrl(miniAppProperties.getMerchantAdminUrl());
            return currentMerchantRes;
        }
        return null;
    }

    @Override
    public MerchantStatisticsRes merchantStatistics(String platformCode) {
        List<MerchantStatisticsDTO> merchantStatisticsDTOS = this.getBaseMapper().merchantStatistics(platformCode);
        MerchantStatisticsRes result = new MerchantStatisticsRes();
        int waitPlatformExamineCount = 0;
        int waitBankExamineCount = 0;
        int normalCount = 0;
        if (CollectionUtils.isNotEmpty(merchantStatisticsDTOS)) {
            waitPlatformExamineCount = merchantStatisticsDTOS.stream().filter(m -> m.getMerchantStatus().equals(MerchantStatusEnums.init.getCode())).mapToInt(MerchantStatisticsDTO::getCount).sum();
            waitBankExamineCount = merchantStatisticsDTOS.stream().filter(m -> m.getMerchantStatus().equals(MerchantStatusEnums.platform_pass.getCode())).mapToInt(MerchantStatisticsDTO::getCount).sum();
            normalCount = merchantStatisticsDTOS.stream().filter(m -> m.getMerchantStatus().equals(MerchantStatusEnums.normal.getCode())).mapToInt(MerchantStatisticsDTO::getCount).sum();
        }
        result.setWaitPlatformExamineCount(waitPlatformExamineCount);
        result.setWaitBankExamineCount(waitBankExamineCount);
        result.setNormalCount(normalCount);
        result.setTotalCount(merchantStatisticsDTOS.stream().mapToInt(MerchantStatisticsDTO::getCount).sum());
        return result;
    }

    @Override
    public List<MerchantSimpleInfoRes> queryMerchantSimpleInfo(QueryMerchantsReq merchantsReq) {
        List<MerchantSimpleInfoRes> merchantSimpleInfoRes = this.getBaseMapper().queryMerchantSimpleInfo(merchantsReq);
        if (CollectionUtils.isNotEmpty(merchantSimpleInfoRes)) {
            for (MerchantSimpleInfoRes merchantSimpleInfoRe : merchantSimpleInfoRes) {
                merchantSimpleInfoRe.setMerchantStatusName(MerchantStatusEnums.getDescByCode(merchantSimpleInfoRe.getMerchantStatus()));
            }
        }
        return merchantSimpleInfoRes;
    }

    @Override
    public String regionData(String dataType) {
        return tradeApiClient.regionData(dataType);
    }

    @Override
    public List<QueryAreaRes> queryByParentAreaCode(String parentAreaCode) {
        return tradeApiClient.queryByParentAreaCode(parentAreaCode);
    }

    @Override
    public List<QueryMccRes> mccList(String mccName) {
        return tradeApiClient.mccList(mccName);
    }

    @Override
    public List<MerchantBranchBankListResVO> branchBankList(MerchantBranchBankListReqVO params) {
        return tradeApiClient.branchBankList(params);
    }

    /**
     * 发起对公账户验证
     *
     * @param params
     */
    @Override
    public void merchantAccountVerify(MerchantAccountVerifyReq params) {
        Optional<Long> treadMerchantAccountVerification = TradeCache.getTreadMerchantAccountVerification(params.getPlatformMerchantId());
        if (treadMerchantAccountVerification.isPresent()) {
            return;
        }
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        Asserts.isTrue(null != payConfig, "商户进件记录不存在！");
        Asserts.isTrue(payConfig.getBankAcctType().equals(1), "仅账户类型为对公账户时可进行该操作！");
        Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.bank_material_supplement.getCode())
                && (payConfig.getMerchantRegStatus().equals(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION.getCode())
                || payConfig.getMerchantRegStatus().equals(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_ING.getCode())
                || payConfig.getMerchantRegStatus().equals(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_FAIL.getCode())), "当前状态不允许进行对公账户验证！");
        // 调用交易中台商户对公账户验证申请
        RequestAccountVerifyReq requestAccountVerifyReq = new RequestAccountVerifyReq();
        requestAccountVerifyReq.setTradeMerchantPayRegId(payConfig.getTradeMerchantPayRegId());
        RequestAccountVerifyResVO tradeRes = tradeApiClient.requestAccountVerify(requestAccountVerifyReq);
        // 成功后，设置当前进件流程节点为对公打款验证中，并缓存4小时
        // 验证成功后清空缓存，并流转到下一个节点状态
        MerchantPayConfig update = new MerchantPayConfig();
        update.setMerchantStatus(MerchantStatusEnums.bank_material_supplement.getCode());
        update.setId(payConfig.getId());
        update.setMerchantRegStatus(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_ING.getCode());
        update.setLastUpdDt(LocalDateTime.now());
        update.setRegCurrentFlows(tradeRes.getCurrentFlow());
        update.setRegNextFlows(tradeRes.getNextFlow());
        merchantPayConfigService.updateById(update);
        TradeCache.cacheTreadMerchantAccountVerification(params.getPlatformMerchantId(), payConfig.getTradeMerchantPayRegId());
        merchantPayRegLogService.saveFlowLog(payConfig.getId(), MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_ING, MerchantRegStatusEnums.INIT, 1);

    }

    /**
     * 商户对公账户交易验证
     *
     * @param params
     */
    @Override
    public Boolean companyAccountVerify(MerchantCompanyAccountVerifyReq params) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        Asserts.isTrue(null != payConfig, "商户进件记录不存在！");
        Asserts.isTrue(payConfig.getBankAcctType().equals(1), "仅账户类型为对公账户时可进行该操作！");
        Asserts.isTrue(payConfig.getMerchantStatus().equals(MerchantStatusEnums.bank_material_supplement.getCode())
                && payConfig.getMerchantRegStatus().equals(MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_ING.getCode()), "当前状态不允许进行对公账户验证！");
        // 调用交易中台商户对公账户验证申请
        RequestCompanyAccountVerifyRequest request = new RequestCompanyAccountVerifyRequest();
        request.setTradeMerchantPayRegId(payConfig.getTradeMerchantPayRegId());
        request.setTransAmt(params.getAmount().multiply(new BigDecimal(100)).intValue());
        CompanyAccountVerifyResVO tradeRes = tradeApiClient.companyAccountVerify(request);
        // 成功后，设置当前进件流程节点为对公打款验证中，并缓存4小时
        // 验证成功后清空缓存，并流转到下一个节点状态
        MerchantPayConfig update = new MerchantPayConfig();
        update.setId(payConfig.getId());
        update.setMerchantStatus(MerchantStatusEnums.bank_material_supplement.getCode());
        update.setMerchantRegStatus(MerchantRegStatusEnums.SIGNING_IN_PROGRESS.getCode());
        update.setLastUpdDt(LocalDateTime.now());
        update.setRegCurrentFlows(tradeRes.getCurrentFlow());
        update.setRegNextFlows(tradeRes.getNextFlow());
        merchantPayConfigService.updateById(update);
        TradeCache.removeTreadMerchantAccountVerification(params.getPlatformMerchantId());
        merchantPayRegLogService.saveFlowLog(payConfig.getId(), MerchantRegStatusEnums.SIGNING_IN_PROGRESS, MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION, 1);
        return true;
    }

    @Transactional
    @Override
    public String agreementSign(MerchantPayAgreementSignReq params) {
        AgreementSignSourceEnums agreementSignSourceEnums = AgreementSignSourceEnums.getByCode(params.getAgreementSignSource());
        Asserts.isTrue(null != agreementSignSourceEnums, "不支持的签约端类型！当前支持：PC、H5");
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(params.getPlatformMerchantId());
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        Asserts.isTrue(null != payConfig, "商户进件记录不存在！");
        // 状态校验
        Asserts.isTrue(payConfig.getRegCurrentFlows().equals(MerchantRegStatusEnums.SIGNING_IN_PROGRESS.getCode()) || payConfig.getRegNextFlows().equals(MerchantRegStatusEnums.SIGNING_IN_PROGRESS.getCode()), "商户当前状态不允许进行签约操作！");
        // 调用交易中台商户对公账户验证申请
        MerchantPayRegAgreementSignReq request = new MerchantPayRegAgreementSignReq();
        request.setTradeMerchantPayRegId(payConfig.getTradeMerchantPayRegId());
        request.setAgreementSignSource(params.getAgreementSignSource());
        MerchantAgreementSignResVO tradeRes = tradeApiClient.agreementSign(request);
        // 成功后，设置当前进件流程节点为对公打款验证中，并缓存4小时
        // 验证成功后清空缓存，并流转到下一个节点状态
        MerchantPayConfig update = new MerchantPayConfig();
        update.setId(payConfig.getId());
        update.setMerchantStatus(MerchantStatusEnums.bank_material_supplement.getCode());
        update.setMerchantRegStatus(MerchantRegStatusEnums.SIGNING_IN_PROGRESS.getCode());
        update.setLastUpdDt(LocalDateTime.now());
        update.setRegCurrentFlows(tradeRes.getCurrentFlow());
        update.setRegNextFlows(tradeRes.getNextFlow());
        merchantPayConfigService.updateById(update);
        merchantPayRegLogService.saveFlowLog(payConfig.getId(), MerchantRegStatusEnums.SIGNING_IN_PROGRESS, MerchantRegStatusEnums.CORPORATE_ACCOUNT_VERIFICATION_SUCCESS, 1);
        return tradeRes.getSignUrl();
    }

    /**
     * 查询商户进件状态
     *
     * @param platformMerchantId 平台商户id
     * @return
     */
    @Override
    public MerchantRegStatusRes queryMerchantStatus(Long platformMerchantId) {
        // 判断平台是否存在
        final PlatformMerchant platformMerchant = platformMerchantService.getById(platformMerchantId);
        Asserts.isTrue(null != platformMerchant && Objects.nonNull(platformMerchant.getId()), "平台关联商户不存在！");
        final Platform platform = platformService.getOneByPlatformCode(platformMerchant.getPlatformCode());
        final MerchantPayConfig payConfig = merchantPayConfigService.getByMerchantCodeAndPlatformPayChannelIdl(platformMerchant.getMerchantCode(), platform.getOrgPaymentChannelId());
        Asserts.isTrue(null != payConfig, "商户进件记录不存在！");
        MerchantRegStatusQueryRes merchantRegStatusQueryRes = tradeApiClient.queryRegisterMerchantByTradeRegId(payConfig.getTradeMerchantPayRegId());

        MerchantRegStatusRes merchantRegStatusRes = new MerchantRegStatusRes();
        return merchantRegStatusRes;
    }

    /**
     * 查询商户进件信息
     *
     * @param platformCode 平台编码
     * @param merchantCode 商户编码
     * @return
     */
    public MerchantAddStepOneRes queryByPlatformCodeAndMerchantCode(String platformCode, String merchantCode) {
        final Platform platform = platformService.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformCode));
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, merchantCode));
        return queryByMerchantAndPlatform(platform, merchant);
    }

    @Override
    public MerchantAddStepOneRes queryByPlatformMerchantId(Long platformMerchantId) {
        PlatformMerchant platformMerchant = platformMerchantService.getById(platformMerchantId);
        final Platform platform = platformService.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformMerchant.getPlatformCode()));
        final Merchant merchant = this.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMerchantCode, platformMerchant.getMerchantCode()));
        return queryByMerchantAndPlatform(platform, merchant);
    }

    private MerchantAddStepOneRes queryByMerchantAndPlatform(Platform platform, Merchant merchant) {
        if (Objects.isNull(merchant)) {
            return null;
        }
        final MerchantAddStepOneRes merchantAddStepOneRes = MerchantConvert.INSTANCE.merchant2MerchantAddStepOneRes(merchant);
        final PlatformMerchant platformMerchant = platformMerchantService.getOne(new LambdaQueryWrapper<PlatformMerchant>().eq(PlatformMerchant::getPlatformCode, platform.getPlatformCode()).eq(PlatformMerchant::getMerchantCode, merchant.getMerchantCode()));
        if (null != platformMerchant) {
            merchantAddStepOneRes.setPlatformMerchantId(platformMerchant.getId());
            merchantAddStepOneRes.setPlatformCode(platformMerchant.getPlatformCode());
        }
        final List<MerchantPayConfig> merchantPayConfigs = merchantPayConfigService.list(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getMerchantCode, merchant.getMerchantCode()).eq(MerchantPayConfig::getPlatformPayChannelId, platform.getOrgPaymentChannelId()));
        if (!CollectionUtils.isEmpty(merchantPayConfigs)) {
            final MerchantPayConfig merchantPayConfig = merchantPayConfigs.get(0);
            merchantAddStepOneRes.setShopProvinceId(merchantPayConfig.getShopProvinceId());
            merchantAddStepOneRes.setShopCityId(merchantPayConfig.getShopCityId());
            merchantAddStepOneRes.setShopCountryId(merchantPayConfig.getShopCountryId());
            merchantAddStepOneRes.setShopAddress(merchantPayConfig.getShopAddress());
            merchantAddStepOneRes.setShopLicenseBeginDate(merchantPayConfig.getShopLicenseBeginDate());
            merchantAddStepOneRes.setShopLicenseEndDate(merchantPayConfig.getShopLicenseEndDate());
            merchantAddStepOneRes.setShopBusiness(merchantPayConfig.getShopBusiness());
            merchantAddStepOneRes.setTradeMerchantCode(merchantPayConfig.getTradeMerchantCode());
            merchantAddStepOneRes.setTradeChannelCode(merchantPayConfig.getTradeChannelCode());
            merchantAddStepOneRes.setTradeChannelName(merchantPayConfig.getTradeChannelName());
            merchantAddStepOneRes.setBankNo(merchantPayConfig.getBankNo());
            merchantAddStepOneRes.setBankAcctNo(merchantPayConfig.getBankAcctNo());
            merchantAddStepOneRes.setBankAcctName(merchantPayConfig.getBankAcctName());
            merchantAddStepOneRes.setBankAcctPhone(merchantPayConfig.getBankAcctPhone());
            merchantAddStepOneRes.setLegalOccupation(merchant.getLegalOccupation());
            merchantAddStepOneRes.setMerchantStatus(merchantPayConfig.getMerchantStatus());
            merchantAddStepOneRes.setMerchantStatusDescribe(merchantPayConfig.getMerchantStatusDescribe());
            merchantAddStepOneRes.setMccCode(merchantPayConfig.getMccCode());
            merchantAddStepOneRes.setMerchantRegStatus(merchantPayConfig.getMerchantRegStatus());

            final List<MerchantPayCert> list = merchantPayCertService.list(new LambdaQueryWrapper<MerchantPayCert>().eq(MerchantPayCert::getMerchantPayConfigId, merchantPayConfig.getId()));
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.sh_yyzz.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setBusinessLicense(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.fr_sfz.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setIdCardPositive(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.fr_sfz_fm.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setIdCardBack(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.yhk_zmz.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setBankCardPositiveUrl(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.yhk_bmz.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setBankCardBackUrl(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.khxkz.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setAccountOpeningLicense(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.fzzmcl.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setAuxiliaryMaterialsImg(f.getInnerFilePath());
            });
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.fzzmcl1.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setAuxiliaryMaterialsImg1(f.getInnerFilePath());
            });
            // 网站、APP截图
            list.stream().filter(f -> f.getCertType().equals(IdPhotoEnums.wzapp.getCode())).findFirst().ifPresent(f -> {
                merchantAddStepOneRes.setWebsiteImg(f.getInnerFilePath());
            });
            List<MerchantAddFileRes> fileList = new ArrayList<>();
            for (MerchantPayCert merchantPayCert : list) {
                MerchantAddFileRes item = new MerchantAddFileRes();
                item.setDocumentType(merchantPayCert.getCertType());
                item.setFileId(merchantPayCert.getFileId());
                item.setUrl(merchantPayCert.getInnerFilePath());
                item.setDocumentName(merchantPayCert.getCertName());
                fileList.add(item);
            }
            merchantAddStepOneRes.setFileList(fileList);
        }
        setRegionName(merchantAddStepOneRes);
        setMccName(merchantAddStepOneRes);
        // 商户超级管理员
        final PlatformMerchantUserDetailDTO platformMerchantUser = platformMerchantUserService.queryPlatformMerchantSuperAdmin(platformMerchant.getId());
        merchantAddStepOneRes.setMerchantSuperAdmin(platformMerchantUser);
        final PlatformMerchantSettleRule platformMerchantSettleRule = platformMerchantSettleRuleService.currentRule(platformMerchant.getId());
        if (null != platformMerchantSettleRule) {
            merchantAddStepOneRes.setPlatformPercent(platformMerchantSettleRule.getPlatformPercent());
        }
        return merchantAddStepOneRes;
    }

    private void setRegionName(MerchantAddStepOneNewRes m) {
        StringBuilder areaCods = new StringBuilder();
        if (StringUtils.isNotEmpty(m.getShopProvinceId())) {
            areaCods.append(m.getShopProvinceId()).append(",");
        }
        if (StringUtils.isNotEmpty(m.getShopCityId())) {
            areaCods.append(m.getShopCityId()).append(",");
        }
        if (StringUtils.isNotEmpty(m.getShopCountryId())) {
            areaCods.append(m.getShopCountryId()).append(",");
        }
        if (StringUtils.isNotEmpty(areaCods)) {
            List<QueryAreaRes> list = tradeApiClient.queryRegionByCodes(areaCods.toString());
            if (CollectionUtils.isNotEmpty(list)) {
                list.stream().filter(l -> StringUtils.isNotEmpty(m.getShopProvinceId()) && l.getAreaCode().equals(m.getShopProvinceId())).findFirst().ifPresent(l -> {
                    m.setShopProvinceName(l.getAreaName());
                });
                list.stream().filter(l -> StringUtils.isNotEmpty(m.getShopCityId()) && l.getAreaCode().equals(m.getShopCityId())).findFirst().ifPresent(l -> {
                    m.setShopCityName(l.getAreaName());
                });
                list.stream().filter(l -> StringUtils.isNotEmpty(m.getShopCountryId()) && l.getAreaCode().equals(m.getShopCountryId())).findFirst().ifPresent(l -> {
                    m.setShopCountryName(l.getAreaName());
                });
            }
        }
    }

    private void setMccName(MerchantAddStepOneRes m) {
        if (StringUtils.isNotEmpty(m.getMccCode())) {
            List<QueryMccRes> mccResList = tradeApiClient.queryMccByCode(m.getMccCode());
            if (CollectionUtils.isNotEmpty(mccResList)) {
                m.setMccName(mccResList.get(0).getMccName());
            }
        }

    }

    private void setMccName(PlatformMerchantBusinessInfoRes m) {
        if (StringUtils.isNotEmpty(m.getMccCode())) {
            List<QueryMccRes> mccResList = tradeApiClient.queryMccByCode(m.getMccCode());
            if (CollectionUtils.isNotEmpty(mccResList)) {
                m.setMccName(mccResList.get(0).getMccName());
            }
        }

    }

    private MerchantAddStepOneNewRes queryByMerchantAndPlatformNew(Platform platform, Merchant merchant) {
        if (Objects.isNull(merchant)) {
            return null;
        }
        final MerchantAddStepOneNewRes merchantAddStepOneRes = MerchantConvert.INSTANCE.merchant2MerchantAddStepOneNewRes(merchant);
        final PlatformMerchant platformMerchant = platformMerchantService.getOne(new LambdaQueryWrapper<PlatformMerchant>().eq(PlatformMerchant::getPlatformCode, platform.getPlatformCode()).eq(PlatformMerchant::getMerchantCode, merchant.getMerchantCode()));
        if (null != platformMerchant) {
            merchantAddStepOneRes.setPlatformMerchantId(platformMerchant.getId());
            merchantAddStepOneRes.setPlatformCode(platformMerchant.getPlatformCode());
        }
        final List<MerchantPayConfig> merchantPayConfigs = merchantPayConfigService.list(new LambdaQueryWrapper<MerchantPayConfig>().eq(MerchantPayConfig::getMerchantCode, merchant.getMerchantCode()).eq(MerchantPayConfig::getPlatformPayChannelId, platform.getOrgPaymentChannelId()));
        if (!CollectionUtils.isEmpty(merchantPayConfigs)) {
            final MerchantPayConfig merchantPayConfig = merchantPayConfigs.get(0);
            merchantAddStepOneRes.setShopProvinceId(merchantPayConfig.getShopProvinceId());
            merchantAddStepOneRes.setShopCityId(merchantPayConfig.getShopCityId());
            merchantAddStepOneRes.setShopCountryId(merchantPayConfig.getShopCountryId());
            merchantAddStepOneRes.setShopAddress(merchantPayConfig.getShopAddress());
            merchantAddStepOneRes.setShopLicenseBeginDate(merchantPayConfig.getShopLicenseBeginDate());
            merchantAddStepOneRes.setShopLicenseEndDate(merchantPayConfig.getShopLicenseEndDate());
            merchantAddStepOneRes.setShopBusiness(merchantPayConfig.getShopBusiness());
            merchantAddStepOneRes.setTradeMerchantCode(merchantPayConfig.getTradeMerchantCode());
            merchantAddStepOneRes.setTradeChannelCode(merchantPayConfig.getTradeChannelCode());
            merchantAddStepOneRes.setTradeChannelName(merchantPayConfig.getTradeChannelName());
            merchantAddStepOneRes.setBankNo(merchantPayConfig.getBankNo());
            merchantAddStepOneRes.setBankAcctNo(merchantPayConfig.getBankAcctNo());
            merchantAddStepOneRes.setBankAcctName(merchantPayConfig.getBankAcctName());
            merchantAddStepOneRes.setBankAcctPhone(merchantPayConfig.getBankAcctPhone());
            merchantAddStepOneRes.setLegalOccupation(merchant.getLegalOccupation());
            merchantAddStepOneRes.setMerchantStatus(merchantPayConfig.getMerchantStatus());
            merchantAddStepOneRes.setMerchantStatusDescribe(merchantPayConfig.getMerchantStatusDescribe());


            final List<MerchantPayCert> list = merchantPayCertService.list(new LambdaQueryWrapper<MerchantPayCert>().eq(MerchantPayCert::getMerchantPayConfigId, merchantPayConfig.getId()));
            List<MerchantAddFileRes> fileList = new ArrayList<>();
            for (MerchantPayCert merchantPayCert : list) {
                MerchantAddFileRes item = new MerchantAddFileRes();
                item.setDocumentType(merchantPayCert.getCertType());
                item.setFileId(merchantPayCert.getFileId());
                item.setUrl(merchantPayCert.getInnerFilePath());
                item.setDocumentName(merchantPayCert.getCertName());
                fileList.add(item);
            }
            setRegionName(merchantAddStepOneRes);
            merchantAddStepOneRes.setFileList(fileList);
        }
        // 商户超级管理员
        final PlatformMerchantUserDetailDTO platformMerchantUser = platformMerchantUserService.queryPlatformMerchantSuperAdmin(platformMerchant.getId());
        merchantAddStepOneRes.setMerchantSuperAdmin(platformMerchantUser);
        final PlatformMerchantSettleRule platformMerchantSettleRule = platformMerchantSettleRuleService.currentRule(platformMerchant.getId());
        if (null != platformMerchantSettleRule) {
            merchantAddStepOneRes.setPlatformPercent(platformMerchantSettleRule.getPlatformPercent());
        }
        return merchantAddStepOneRes;
    }

    private List<MerchantPayCert> saveCerts(Merchant merchant, MerchantAddReqNew params, Platform platform, List<MerchantPayRegFileResVO> files) {
        //商户在该平台还没注册过，注册
        final MerchantPayConfig merchantPayConfig = MerchantConvert.INSTANCE.convert2MerchantPayConfig(params);
        merchantPayConfig.setMerchantCode(merchant.getMerchantCode());
        merchantPayConfig.setCreatedDt(LocalDateTime.now());
        merchantPayConfig.setPlatformPayChannelId(platform.getOrgPaymentChannelId());
        merchantPayConfig.setShopBusiness(params.getShopBusiness());
        merchantPayConfig.setBankAcctType(merchant.getMerchantType().equals(3) ? 0 : 1);
        merchantPayConfig.setBankNo(params.getBankNo());
        merchantPayConfig.setBankAcctNo(params.getBankAcctNo());
        merchantPayConfig.setBankAcctName(params.getBankAcctName());
        merchantPayConfig.setBankAcctPhone(params.getBankAcctPhone());
        merchantPayConfig.setTradeChannelCode(platform.getPaymentChannelCode());
        merchantPayConfig.setTradeChannelName(platform.getPaymentChannelName());
        // 行业：7991-旅游与展览
        merchantPayConfig.setMccCode(StringUtils.isEmpty(params.getMccCode()) ? "7991" : params.getMccCode());
        merchantPayConfigService.save(merchantPayConfig);
        // 保存证件照信息
        final List<MerchantPayCert> merchantPayCerts = new ArrayList<>(files.size());
        for (MerchantPayRegFileResVO file : files) {
            MerchantPayCert merchantPayCert = new MerchantPayCert();
            merchantPayCert.setFileId(file.getId().toString());
            merchantPayCert.setCreatedDt(LocalDateTime.now());
            merchantPayCert.setMerchantPayConfigId(merchantPayConfig.getId());
            merchantPayCert.setCertType(file.getDocumentType());
            merchantPayCert.setCertName(file.getFileName());
            merchantPayCert.setFilePath(file.getInnerFilePath());
            merchantPayCert.setInnerFilePath(file.getInnerFilePath());
            merchantPayCert.setCreatedDt(LocalDateTime.now());
            merchantPayCerts.add(merchantPayCert);
        }
        merchantPayCertService.saveBatch(merchantPayCerts);
        return merchantPayCerts;
    }

    private MerchantPayCert getMerchantPayCert(IdPhotoEnums photoEnums, String url) {
        final MerchantPayCert merchantPayCert = new MerchantPayCert();
        merchantPayCert.setCertType(photoEnums.getCode());
        merchantPayCert.setCertName(photoEnums.getName());
        merchantPayCert.setFilePath(url);
        merchantPayCert.setInnerFilePath(url);
        merchantPayCert.setCreatedDt(LocalDateTime.now());
        return merchantPayCert;
    }

}
